<template>
  <div class="relative inline-block text-left"
    ref="select">
    <div :class="{'selected': isSelected}"
      class="group">
      <button type="button"
        class="dropdown inline-flex items-center w-full justify-center bg-gray-2100 px-3 text-sm font-medium text-gray-1000 hover:bg-purple-100 hover:bg-purple-1300 hover:text-white group-hover:bg-purple-1300 group-hover:text-white to-show-options"
        :class="{'border':hasBorder, 'border-gray-1300':hasBorder, 'shadow-sm':hasBorder}"
        @click="showOptions">
        <span class="whitespace-nowrap truncate">{{resetLabel()}}</span>

        <svg class="-mr-1 ml-2 h-5 w-5 arrow"
          viewBox="0 0 20 20"
          fill="currentColor"
          aria-hidden="true"
          :class="{show:targetObj.isShowOptions}">
          <path fill-rule="evenodd"
            d="M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z"
            clip-rule="evenodd" />
        </svg>
      </button>

      <span @click="del"
        v-if="isSelected"
        class="to-reset">
        <svg-icon className="delBtn"
          iconName='delete_white'></svg-icon>
      </span>
    </div>

    <div class="absolute left-0 z-10 mt-2 min-w-full origin-top-right rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none optionsMax"
      role="menu"
      aria-orientation="vertical"
      tabindex="-1"
      v-show="targetObj.isShowOptions">
      <div class="py-1"
        role="none">
        <common-link :path="$route.params.lang?$route.path.replace(`/${$route.params.lang}`,''):$route.path"
          :query="tItem.query"
          v-for="(tItem,key) in menuList"
          :key="key"
          class="text-gray-1000 block px-4 py-2 text-sm duration-100 hover:text-purple-1300 whitespace-nowrap go-attributes-search"
          :class="{'text-purple-1300': resetStatus(tItem),'font-semibold': resetStatus(tItem),'hover:opacity-90': resetStatus(tItem)}">
          {{tItem.name}}
        </common-link>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'CommonSelect',
  props: {
    targetObj: {
      type: Object,
      default: {},
    },
    attributesList: {
      type: Array,
      default() {
        return []
      },
    },
    //是否有边框
    hasBorder: {
      type: Boolean,
      default: true,
    },
    //是否有边框
    selectType: {
      type: String,
      default: 'attributes',
    },
  },
  watch: {
    '$route.query': {
      handler(val) {
        this.targetObj.isShowOptions = false
      },
      immediate: true,
      deep: true,
    },
  },
  computed: {
    isSelected() {
      let attributesVal = this.$route.query.attributes
      let linkAttributesArr = []
      if (attributesVal) {
        linkAttributesArr = attributesVal.split(',')
      }
      let isHandle = false
      linkAttributesArr.forEach((item, key) => {
        if (item.indexOf(`${this.targetObj.handle}-`) === 0) {
          isHandle = true
        }
      })
      return isHandle
    },
    menuList() {
      /* 链接中含有的属性 */
      let newPath = { ...this.$route.query }
      let linkAttributesArr = []
      if (newPath.attributes) {
        linkAttributesArr = newPath.attributes.split(',')
      }
      /* 链接属性中是否已有该大类 */
      let isHandle = false
      linkAttributesArr.forEach((item, key) => {
        if (item.indexOf(`${this.targetObj.handle}-`) === 0) {
          isHandle = true
        }
      })
      let attributesArr = []
      if (this.attributesList && this.attributesList.length > 0) {
        this.attributesList.forEach((item) => {
          attributesArr.push(item.handle)
        })
      }

      /* 链接属性中是否已有该大类 end */
      if (
        this.targetObj &&
        this.targetObj.options &&
        this.targetObj.options.length > 0
      ) {
        let options = JSON.parse(JSON.stringify(this.targetObj.options))
        options.forEach((tItem) => {
          let val = `${this.targetObj.handle}-${tItem.handle}`
          let query = JSON.parse(JSON.stringify(linkAttributesArr))
          if (query && query.length > 0 && isHandle) {
            query.forEach((item, key) => {
              if (item.indexOf(`${this.targetObj.handle}-`) === 0) {
                if (item === val) {
                  query.splice(key, 1)
                } else {
                  query[key] = val
                }
              }
            })
          } else {
            query.push(val)
          }

          let newPath = { ...this.$route.query }
          newPath.attributes = query.join(',')

          for (let key in newPath) {
            if (newPath[key] === null || newPath[key] === '') {
              delete newPath[key]
            }
          }
          tItem.query = { ...newPath }
        })
        return options
      } else {
        return []
      }
    },
  },
  mounted() {
    document.addEventListener('click', this.handleClick)
  },
  methods: {
    handleClick(event) {
      if (this.$refs.select) {
        let self = this.$refs.select.contains(event.target)
        if (!self) {
          this.targetObj.isShowOptions = false
        }
      }
    },
    showOptions() {
      this.targetObj.isShowOptions = !this.targetObj.isShowOptions
    },
    resetLabel() {
      let attributesVal = this.$route.query.attributes

      let attributesArr = []
      let fVal
      if (attributesVal) {
        attributesArr = attributesVal.split(',')
        attributesArr.forEach((item) => {
          if (item.indexOf(`${this.targetObj.handle}-`) === 0) {
            fVal = item
          }
        })
      }
      if (fVal) {
        let tIndex = this.targetObj.options.findIndex((item) => {
          return `${this.targetObj.handle}-${item.handle}` === fVal
        })
        if (tIndex >= 0) {
          return this.targetObj.options[tIndex].name
        } else {
          return this.targetObj.name
        }
      } else {
        return this.targetObj.name
      }
    },
    del() {
      let newPath = { ...this.$route.query }
      let attributes = newPath.attributes

      let obj = this.menuList.find((item) => {
        let val = `${this.targetObj.handle}-${item.handle}`
        return attributes.indexOf(val) >= 0
      })
      if (obj) {
        this.$router.push({
          name: this.$route.name,
          query: {
            ...obj.query,
          },
        })
      }
    },
    resetStatus(tItem) {
      let newPath = { ...this.$route.query }
      let val = `${this.targetObj.handle}-${tItem.handle}`
      let urlAttributes = []
      if (newPath.attributes) {
        urlAttributes = newPath.attributes.split(',')
      }
      let tIndex = urlAttributes.findIndex((item) => {
        return item === val
      })
      if (tIndex >= 0) {
        return true
      } else {
        return false
      }
    },
    /* 属性 end */
  },
  beforeDestroy() {
    document.removeEventListener('click', this.handleClick)
  }
}
</script>
<style lang='scss' scoped>
.dropdown {
  height: 34px;
  border-radius: 17px;
  svg {
    transition: 0.2s;
    &.show {
      transform: rotate(180deg);
    }
  }
}
.delBtn {
  display: none;
}
.selected {
  position: relative;
  font-size: 0;
  &:hover {
    button {
      padding-right: 36px !important;
      transition: all 0 !important;
    }
    .arrow {
      display: none !important;
      transition: all 0 !important;
    }
    .delBtn {
      position: absolute;
      right: 10px;
      top: 17px;
      transform: translateY(-50%);
      display: block;
      font-size: 20px;
      color: #fff;
      border-radius: 50%;
      cursor: pointer;
    }
  }
}
</style>
